const crypto = require('crypto');
const Config  = require("./config");
var fs = require("fs");
    var nodemailer = require('nodemailer')
    var smtpTransport = require('nodemailer-smtp-transport');

let _ ={
   success: function(msg, entity) {
        let _ret = {
            result: {
                code: 0,
                msg: msg || ""
            }
        };
        if (entity) {
            _ret.entity = entity;
        }
        return _ret;
    },
    error: function(msg) {
        let _error = {
            result: {
                code: 1,
                msg: msg || ""
            }
        };
        return _error;
    },
    notLogin: function(msg) {
        let _error = {
            result: {
                code: 2,
                msg: msg || ""
            }
        };
        return _error;
    } 
}



/**
* 图像验证加密
* @return {string} 
*/
_.buildEncryptParam = ()=>{
    //配置
    var appid =  Config.youtu_appid;
    var SecretID = Config.youtu_secretId;
    var secretKey = Config.youtu_secretKey;
    var puserid =  Config.youtu_userid;
    var now = parseInt(Date.now() / 1000);
    var random = parseInt(Math.random() * Math.pow(2, 32));
    var expired = now + (60 * 60 * 24 * 30);
    var plainText = "a=" + appid + "&k=" + SecretID + "&e=" + expired + "&t=" + now + "&r=" + random + '&u=' + puserid;
    var _data = new Buffer(plainText, 'utf8');
    var _temp = crypto.createHmac('sha1', secretKey).update(_data).digest();
    var bin = Buffer.concat([_temp, _data]);
    let _sign = bin.toString('base64');
    return _sign;
}

/**
* 保存base64图片->文件:异步保存
*/
_.saveImg = (img)=>{
     let imagePath = img;
     let _buffer = new Buffer(imagePath,"base64");
     let _path = Config.uploadPath;
     dateFormat();
     let _name = (new Date()).Format('yyyy-M-d-h')+Math.floor(Math.random()*100+1)+".png";
     function mkDir(){
        return new Promise((resolve,reject)=>{
            fs.stat(_path,function(err,stats){
                if(err){
                    console.error("fs.stat:"+err);
                    fs.mkdir(_path,function(err){  
                        if(err){
                            console.error(err);  
                            reject();
                        }
                        resolve();
                        console.log('创建目录成功');  
                    });  
                }else{
                    resolve();
                }
            });
        })
     }
    mkDir().then(()=>{
     fs.writeFile(_path+_name,_buffer,function(err){
        if(err){
          console.log(err);
        }else{
            console.log("保存成功:"+_path+_name);
            return "_path+_name";
        }
     })
    }).catch(err=>{
       console.log(err);
       return "";
    });
}

_.dateFormat = ()=>{
    // 对Date的扩展，将 Date 转化为指定格式的String  
    // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，  
    // 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)  
    // 例子：  
    // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423  
    // (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18  
    Date.prototype.Format = function(fmt)  
    { //author: meizz  
        var o = {  
            "M+" : this.getMonth()+1,                 //月份  
            "d+" : this.getDate(),                    //日  
            "h+" : this.getHours(),                   //小时  
            "m+" : this.getMinutes(),                 //分  
            "s+" : this.getSeconds(),                 //秒  
            "q+" : Math.floor((this.getMonth()+3)/3), //季度  
            "S"  : this.getMilliseconds()             //毫秒  
        };  
        if(/(y+)/.test(fmt))  
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));  
        for(var k in o)  
            if(new RegExp("("+ k +")").test(fmt))  
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));  
        return fmt;  
    };  
  
// console.log(date.Format('yyyy-MM-dd hh:mm:ss.S q'));  
// console.log(date.Format('yyyy-M-d h:m:s.S q'));  
}

/**
 * @param {String} recipient 收件人
 * @param {String} subject 发送的主题
 * @param {String} html 发送的html内容
 */
 _.smtpTransport = nodemailer.createTransport(smtpTransport({
        service: 'QQ',
        auth: {
            user: Config.email.user,
            pass: Config.email.pass
        }
    }));
var sendMail = function (recipient, subject, html,callback) {
    _.smtpTransport.sendMail({

        from: Config.email.user,
        to: recipient,
        subject: subject,
        html: html

    }, function (error, response) {
        if (error) {
            console.log(error);
            callback(error)
        }
        console.log('发送成功');
         callback()
    });
}



module.exports=_;